<script lang="ts" setup name="MemberInfoDialog">
import { Avatar } from '@element-plus/icons-vue'
import { FormInstance } from 'element-plus'
import { Dialog } from '~/src/api/interface'
import { Member } from '~/src/api/interface/member'
import { getMemberCategoryAPI, getMemberGradeAPI } from '~/src/api/member'
import { genderType, memberStatus } from '~/src/utils/serviceDict'

const rules = reactive({
  userName: [{ required: true, message: '请填写会员名称' }],
  nickName: [{ required: true, message: '请填写会员昵称' }],
  mobile: [
    { required: true, message: '请输入手机号' },
    {
      validator: (rule: any, value: any, callback: Function) => {
        if (!/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/.test(value)) {
          return callback(new Error('请输入正确的手机号'))
        }
        callback()
      },
    },
  ],
  sex: [{ required: true, message: '请选择性别' }],
  // avatarImage: [{ required: true, message: "请上传头像" }],
  userCategoryId: [{ required: true, message: '请选择会员分类' }],
  grade: [{ required: true, message: '请选择会员等级' }],
  number: [{ required: true, message: '请输入会员卡号' }],
})

interface DialogProps {
  title: string
  isView: boolean
  data: Partial<Member.MemberInfo>
  api?: (params: any) => Promise<any>
  getTableList?: () => void
}

const dialogVisible = ref(false)
const memberGrade = ref<Member.MemberGrade[]>([])
const memberCategory = ref<Member.MemberCategory[]>([])
const dialogProps = ref<Dialog<Partial<Member.MemberInfo>>>({
  title: '',
  data: {},
  visible: false,
})
// 接收父组件传过来的参数
const acceptParams = async (params: Dialog<Partial<Member.MemberInfo>>) => {
  dialogProps.value = params
  const [MemberGrade, MemberCategory] = await Promise.all([
    getMemberGradeAPI({ pageNum: 1, pageSize: 9999 }),
    getMemberCategoryAPI({ ageNum: 1, pageSize: 9999 }),
  ])
  memberGrade.value = MemberGrade.data.list
  memberCategory.value = MemberCategory.data.list
  if (dialogProps.value.title === '新增') {
    dialogProps.value.data.grade = memberGrade.value.length !== 0 ? memberGrade.value[0].id : ''
    dialogProps.value.data.userCategoryId = memberCategory.value.length !== 0 ? memberCategory.value[0].id : 0
  }
  dialogVisible.value = true
}

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>()
const handleSubmit = () => {
  ruleFormRef.value!.validate(async (valid) => {
    if (!valid) return
    try {
      await dialogProps.value.api!(dialogProps.value.data)
      ElMessage.success({ message: `${dialogProps.value.title}会员成功！` })
      dialogProps.value.getTableList!()
      dialogVisible.value = false
    } catch (error) {
      console.log(error)
    }
  })
}

watch(
  () => dialogVisible.value,
  (val) => {
    if (!val) ruleFormRef.value?.resetFields()
  }
)

defineExpose({
  acceptParams,
})
</script>

<template>
  <vab-dialog v-model:modelValue="dialogVisible" :title="`${dialogProps.title}会员`" width="600">
    <el-form
      ref="ruleFormRef"
      label-suffix=" :"
      label-width="100px"
      :model="dialogProps.data"
      :rules="rules"
      style="height: 600px; overflow-y: auto"
    >
      <el-form-item label="会员头像" prop="avatarImage">
        <upload-img v-model:image-url="dialogProps.data!.avatarImage" :file-size="3" height="104px" width="104px">
          <template #empty>
            <el-icon><avatar /></el-icon>
          </template>
          <template #tip>图片大小不能超过 3M</template>
        </upload-img>
      </el-form-item>
      <el-form-item label="会员名称" prop="userName">
        <el-input v-model="dialogProps.data!.userName" clearable placeholder="请填会员名称" />
      </el-form-item>
      <el-form-item label="会员昵称" prop="nickName">
        <el-input v-model="dialogProps.data!.nickName" clearable placeholder="请填会员昵称" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="dialogProps.data!.mobile" clearable placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="dialogProps.data!.sex" class="w100">
          <el-option v-for="item in genderType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="会员等级" prop="grade">
        <el-select v-model="dialogProps.data!.grade" class="w100">
          <el-option v-for="item in memberGrade" :key="item.id" :label="item.title" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="会员分类" prop="userCategoryId">
        <el-select v-model="dialogProps.data!.userCategoryId" class="w100">
          <el-option v-for="item in memberCategory" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="会员卡号" prop="number">
        <el-input v-model="dialogProps.data!.number" clearable placeholder="请输入会员卡号" />
      </el-form-item>
      <el-form-item label="生日" prop="birthday">
        <el-date-picker
          v-model="dialogProps.data!.birthday"
          format="YYYY-MM-DD"
          style="width: 100%"
          type="date"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="dialogProps.data!.status" class="w100" placeholder="请选择会员状态">
          <el-option v-for="item in memberStatus" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="启用日期" prop="starDate">
        <el-date-picker
          v-model="dialogProps.data!.starDate"
          format="YYYY-MM-DD"
          style="width: 100%"
          type="date"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="失效日期" prop="endDate">
        <el-date-picker v-model="dialogProps.data!.endDate" format="YYYY-MM-DD" style="width: 100%" type="date" value-format="YYYY-MM-DD" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </vab-dialog>
</template>

<style lang="scss" scoped></style>
